package mutil

import (
	"fmt"
	"gitee.com/dennis-mxx/mxx-core/mexception"
	"time"
)

var DateUtil = dateUtil{
	DateTimeFormat:           "2006-01-02 15:04:05",
	DateTimeNumber:           "20060102150405",
	DateTimeMillNumberFormat: "060102150405",
	TimeFormat:               "15:04:05",
	TimeFormatNumber:         "150405",
	DateFormat:               "2006-01-02",
	DateFormatNumber:         "20060102",
	CurrentLocation:          "Asia/Shanghai",
}

var DateLocation *time.Location

type dateUtil struct {
	DateTimeFormat           string
	DateTimeNumber           string
	DateTimeMillNumberFormat string
	TimeFormat               string
	TimeFormatNumber         string
	DateFormat               string
	DateFormatNumber         string
	CurrentLocation          string
}

func init() {
	location, error := time.LoadLocation(DateUtil.CurrentLocation)
	if error != nil {
		fmt.Println("[mutil.dateUtil] time load location exception : " + error.Error())
		DateLocation = time.Local
		return
	} else {
		DateLocation = location
	}

}

func (domain dateUtil) NowDateTime() time.Time {
	return time.Now().In(DateLocation)
}
func (domain dateUtil) Format(format string) string {
	return domain.NowDateTime().Format(format)
}
func (domain dateUtil) NowTimestamp() int64 {
	return domain.NowDateTime().Unix()
}
func (domain dateUtil) NowDateTimeStr() string {
	return domain.NowDateTime().Format(domain.DateTimeFormat)
}
func (domain dateUtil) NowDateStr() string {
	return domain.NowDateTime().Format(domain.DateFormat)
}
func (domain dateUtil) NowTimeStr() string {
	return domain.NowDateTime().Format(domain.TimeFormat)
}
func (domain dateUtil) TimestampToDateTime(timestamp int64) time.Time {
	return time.Unix(timestamp, 0).In(DateLocation)
}

func (domain dateUtil) DateTimeToStr(t time.Time) string {
	return t.Format(domain.DateTimeFormat)
}
func (domain dateUtil) DateToStr(t time.Time) string {
	return t.Format(domain.DateFormat)
}
func (domain dateUtil) TimeToStr(t time.Time) string {
	return t.Format(domain.TimeFormat)
}
func (domain dateUtil) StrToDateTime(t string) time.Time {
	tm, err := time.ParseInLocation(domain.DateTimeFormat, t, DateLocation)
	if err != nil {
		panic(mexception.NewErrorEx(mexception.DateTimeFormatException, err))
	}
	return tm
}
func (domain dateUtil) StrFormat(str string, format string) time.Time {
	tm, err := time.ParseInLocation(format, str, DateLocation)
	if err != nil {
		panic(mexception.NewErrorEx(mexception.DateTimeFormatException, err))
	}
	return tm
}

func (domain dateUtil) StrToDate(t string) time.Time {
	tm, err := time.ParseInLocation(domain.DateFormat, t, DateLocation)
	if err != nil {
		panic(mexception.NewErrorEx(mexception.DateTimeFormatException, err))
	}
	return tm
}
func (domain dateUtil) StrToTime(t string) time.Time {
	tm, err := time.ParseInLocation(domain.TimeFormat, t, DateLocation)
	if err != nil {
		panic(mexception.NewErrorEx(mexception.DateTimeFormatException, err))
	}
	return tm
}
